package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.pdm.ec.mapper.TyplmChangeIssueMapper;
import com.hustcad.plm.pdm.ec.module.dto.TyplmChangeIssueDetailDTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.workitem.model.dto.WorkItemQueryDTO;
import com.hustcad.plm.pdm.workitem.model.vo.TyplmWorkItemTaskVO;
import com.hustcad.plm.pdm.workitem.service.TyplmWorkItemService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.change.ChangeIssueDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.type.TypeDO;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.vo.AttributeVO;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.entity.ProblemJurisdictionDO;
import cqrtplm.mapper.PreventErrorCorrectionMapper;
import cqrtplm.mapper.ProblemJurisdictionMapper;
import cqrtplm.mapper.RTFormTemplateMapper;
import cqrtplm.service.ProjectBoardService;
import cqrtplm.util.PageDtoUtil;
import dm.jdbc.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author：lotus
 * @DATE: 2025/7/15 17:55
 */
@Slf4j
@Service
public class ProjectBoardServiceImpl implements ProjectBoardService {


    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private TyplmWorkItemService workItemService;
    @Resource
    private TyplmChangeIssueMapper typlmChangeIssueMapper;
    @Resource
    private RTFormTemplateMapper rtFormTemplateMapper;
    @Resource
    private ProblemJurisdictionMapper problemJurisdictionMapper;
    @Resource
    private PreventErrorCorrectionMapper preventErrorCorrectionMapper;


    /**
     *  获取所有工作任务
     */
    @Override
    public PageDtoUtil queryProjectWorkTask(Integer pageNum, Integer pageSize,TyplmWorkItemTaskVO typlmWorkItemTask) {
        Integer page = 1;
        Integer rows = 10000000;
        UserDO user = TyAccountContext.getUser();

        WorkItemQueryDTO workItemQueryDTO  = new WorkItemQueryDTO();
        workItemQueryDTO.setPageNum(page);
        workItemQueryDTO.setPageSize(rows);
        List<TyplmWorkItemTaskVO> result = new ArrayList<>();

        PageInfo<TyplmWorkItemTaskVO> typlmWorkItemTaskVOPageInfo = workItemService.queryWorkItemPageList(workItemQueryDTO);
        Map<BigInteger, TyplmWorkItemTaskVO> workItemTaskVOMap = typlmWorkItemTaskVOPageInfo.getList().stream().collect(
                Collectors.toMap(TyplmWorkItemTaskVO::getOid, item -> item));
        List<BigInteger> workItemOidList = new ArrayList<>(workItemTaskVOMap.keySet());

        //获取所有工作任务iba属性上报人
        Map<String, List<AttributeVO>> taskIbaMap = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                workItemOidList,
                TableTypeConstrant.TY_PDMLINKPRODUCT_OTYPE,
                Collections.singletonList("SBR"));

        for (TyplmWorkItemTaskVO typlmWorkItemTaskVO : workItemTaskVOMap.values()) {
            BigInteger workItemTaskVOOid = typlmWorkItemTaskVO.getOid();
            if(taskIbaMap.containsKey(workItemTaskVOOid.toString())){
                String attributeValue = taskIbaMap.get(String.valueOf(typlmWorkItemTaskVO.getOid())).get(0).getAttributeValue();
                if (user.getFullname().equals(attributeValue)) {
                    result.add(typlmWorkItemTaskVO);
                    continue;
                }
            }
            if (user.getOid().equals(typlmWorkItemTaskVO.getOwneroid())) {
                result.add(typlmWorkItemTaskVO);
            }
        }

        if (ObjectUtil.isNotEmpty(typlmWorkItemTask)) {
            List<TyplmWorkItemTaskVO> typlmWorkItemTaskVOS = filterPeople(result, typlmWorkItemTask);
            return PageDtoUtil.getPageDto(typlmWorkItemTaskVOS,pageNum,pageSize);
        }

        return PageDtoUtil.getPageDto(result,pageNum,pageSize);
    }

     /*
      获取问题报告
       */
    @Override
    public PageInfo<TyplmChangeIssueDetailDTO> queryProblemReport(Integer pageNum, Integer pageSize) {
        UserDO user = TyAccountContext.getUser();
        List<BigInteger> userIds = new ArrayList<>();
        userIds.add(user.getOid());
        // 获取当前用户的下级用户id
        List<ChangeIssueDO> changeIssueDOS = typlmChangeIssueMapper.selectAll();
        Map<BigInteger, ChangeIssueDO> allIssueDOMap = changeIssueDOS.stream().collect(
                Collectors.toMap(ChangeIssueDO::getOid, item -> item));

        //本来就能看到的
        List<ChangeIssueDO> filteredList = changeIssueDOS.stream()
                .filter(item -> userIds.contains(item.getCreatoroid()))
                .collect(Collectors.toList());
        Map<BigInteger, ChangeIssueDO> result = filteredList.stream().collect(Collectors.toMap(ChangeIssueDO::getOid, item -> item));
        List<ProblemJurisdictionDO> problemJurisdictionDOS = problemJurisdictionMapper.queryProblemJurisdictionByUid(user.getOid());
        if(CollUtil.isNotEmpty(problemJurisdictionDOS)) {
            List<BigInteger> issueOidList = changeIssueDOS.stream().map(ChangeIssueDO::getOid).collect(Collectors.toList());
            List<JSONObject> formDataOfIssue = rtFormTemplateMapper.queryFormDataByIssueOidList(issueOidList);

            for (JSONObject jsonObject : formDataOfIssue) {
                BigInteger oid = jsonObject.getBigInteger("REFOBJBASEOID");
                if(allIssueDOMap.containsKey(oid)) {
                    ChangeIssueDO changeIssueDO = allIssueDOMap.get(oid);
                    BigInteger typeOid = changeIssueDO.getTypeoid();
                    TypeDO typeDO = typlmTypeService.queryTypeByOID(typeOid);
                    if(ObjectUtil.isEmpty(typeDO)) {
                        throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException("类型在系统中不存在:"+typeDO );
                    }
                    String typeName = typeDO.getName();
                    JSONObject formData = jsonObject.getJSONObject("FORMDATA");

                    if (CollUtil.isEmpty(formData)) {
                        continue;
                    }
                    String importance = getAndValidateField(formData, "Importance");
                    importance = Objects.equals(importance, "1") ? "A" : Objects.equals(importance, "2") ? "B" : Objects.equals(
                            importance, "3") ? "C" : importance;

                    //获取问题类型和重要度匹配的问题报告
                    for (ProblemJurisdictionDO jurisdictionDO : problemJurisdictionDOS) {
                        if (StringUtil.isNotEmpty(typeName) && StringUtil.isNotEmpty(importance)) {
                            if (typeName.equals(jurisdictionDO.getIssueReportType())) {
                                if (importance.equals(jurisdictionDO.getProblemLevel())) {
                                    result.put(oid, changeIssueDO);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        log.info("====>符合要求的问题报告：{}" ,result);
        List<BigInteger> currentUserIssueOid = new ArrayList<>(result.keySet());

        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(preventErrorCorrectionMapper.queryChangeIssueInfo(currentUserIssueOid));
    }


    private static String getAndValidateField(JSONObject formJson, String fieldName) {
        if (!formJson.containsKey(fieldName)) {
            return null;
        }
        String value = formJson.getString(fieldName);
        if (value == null || value.isEmpty()) {
            return null;
        }
        return value;
    }


    //筛选list
    private List<TyplmWorkItemTaskVO> filterPeople(List<TyplmWorkItemTaskVO> list,TyplmWorkItemTaskVO vo) {
        // 动态构建 Predicate 组合
        Predicate<TyplmWorkItemTaskVO> predicate = p -> true;  // 初始化为始终true

        // 任务标题
        if (vo.getName() != null && !vo.getName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getName() != null && p.getName().contains(vo.getName())
            );
        }
        //截止日期
        if (vo.getEnddate() != null) {
            predicate = predicate.and(p -> p.getEnddate() != null && DateUtils.isSameDay(p.getEnddate(),vo.getEnddate())
            );
        }
        //紧急程度
        if (vo.getUrgency() != null && !vo.getUrgency().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getUrgency() != null && p.getUrgency().contains(vo.getUrgency())
            );
        }

        //预计工时
        if (vo.getPlanlaborhours() != null && !vo.getPlanlaborhours().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getPlanlaborhours() != null && p.getPlanlaborhours().contains(vo.getPlanlaborhours())
            );
        }
        //实际工时
        if (vo.getRealitylaborhours() != null && !vo.getRealitylaborhours().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getRealitylaborhours() != null && p.getRealitylaborhours().contains(vo.getRealitylaborhours())
            );
        }
        //生命周期状态
        if (vo.getLifecyclestagekeyName() != null && !vo.getLifecyclestagekeyName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getLifecyclestagekeyName() != null && p.getLifecyclestagekeyName().contains(vo.getLifecyclestagekeyName())
            );
        }
        //当前节点
        if (vo.getTaskName() != null && !vo.getTaskName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getTaskName() != null && p.getTaskName().contains(vo.getTaskName())
            );
        }
        //执行人
        if (vo.getExecutorFullName() != null && !vo.getExecutorFullName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getExecutorFullName() != null && p.getExecutorFullName().contains(vo.getExecutorFullName())
            );
        }
        //负责人
        if (vo.getOwnerFullName() != null && !vo.getOwnerFullName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getOwnerFullName() != null && p.getOwnerFullName().contains(vo.getOwnerFullName())
            );
        }
        //实际开始时间
        if (vo.getRealstartdate() != null) {
            predicate = predicate.and(p ->
                                              p.getRealstartdate() != null && DateUtils.isSameDay(p.getRealstartdate(),vo.getRealstartdate())
            );
        }
        //实际完成时间
        if (vo.getFinishdate() != null) {
            predicate = predicate.and(p ->
                                              p.getFinishdate() != null && DateUtils.isSameDay(p.getFinishdate(),vo.getFinishdate())
            );
        }
        //类型
        if (vo.getTypeDefName() != null && !vo.getTypeDefName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getTypeDefName() != null && p.getTypeDefName().contains(vo.getTypeDefName())
            );
        }
        //开始日期
        if (vo.getStartdate() != null) {
            predicate = predicate.and(p ->
                                              p.getStartdate() != null && DateUtils.isSameDay(p.getStartdate(),vo.getStartdate())
            );
        }
        //发起者
        if (vo.getCreatorFullName() != null && !vo.getCreatorFullName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getCreatorFullName() != null && p.getCreatorFullName().contains(vo.getCreatorFullName())
            );
        }
        //上下文
        if (vo.getContainerName() != null && !vo.getContainerName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getContainerName() != null && p.getContainerName().contains(vo.getContainerName())
            );
        }
        //创建时间
        if (vo.getCreatestamp() != null ) {
            predicate = predicate.and(p ->
                                              p.getCreatestamp() != null && DateUtils.isSameDay(p.getCreatestamp(),vo.getCreatestamp())
            );
        }
        //编号
        if (vo.getObjectnumber() != null && !vo.getObjectnumber().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getObjectnumber() != null && p.getObjectnumber().contains(vo.getObjectnumber())
            );
        }


        // 应用筛选条件
        return list.stream()
                .filter(predicate)
                .collect(Collectors.toList());
    }
}
